package com.xxrl.shop.controller;

import com.alibaba.fastjson.JSONArray;
import com.xxrl.shop.common.entity.JsonResult;
import com.xxrl.shop.common.utils.ResultTool;
import com.xxrl.shop.domain.Cart;
import com.xxrl.shop.service.CartService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * 购物车
 * @author mis
 */
@Api(tags = {"cart"})
@RestController
@RequestMapping("/cart")
public class CartController {

    private final CartService cartService;

    public CartController(CartService cartService) {
        this.cartService = cartService;
    }

    @ApiOperation(value = "Remove one item in cart")
    @PostMapping("del")
    public JsonResult<String> del(Long userId, Long productId) {
        cartService.deleteCart(userId, productId);
        return ResultTool.success();
    }

    @ApiOperation(value = "Clear items in cart")
    @PostMapping("delAll")
    public JsonResult<String> delAll(Long userId) {
        cartService.deleteAllCart(userId);
        return ResultTool.success();
    }

    @ApiOperation(value = "List all items in user cart.", response = Cart.class,
            responseContainer = "List")
    @GetMapping("list")
    public JsonResult<String> list(Long userId) {
        List<Cart> carts = cartService.listCart(userId);
        JSONArray jsonArray = new JSONArray();
        jsonArray.addAll(carts);
        return ResultTool.success(jsonArray.toString());
    }

    @ApiOperation(value = "Update one cart item")
    @PostMapping("edit")
    public JsonResult<String> edit(Long userId, Long productId, Boolean checked, Integer productNum) {
        cartService.saveCart(userId, productId, checked, productNum);
        return ResultTool.success("OK");
    }

    @ApiOperation(value = "Check all cart items")
    @PostMapping("checkAll")
    public JsonResult<String> checkAll(Long userId, Boolean checkAll) {
        cartService.updateCheck(userId, checkAll);
        return  ResultTool.success();
    }

    @ApiOperation(value = "Add a new cart item")
    @PostMapping("add")
    public JsonResult<String> add(Cart cart) {
        if (cart.getProductNum() == null) {
            cart.setProductNum(1);
        }
        if (cart.getChecked() == null) {
            cart.setChecked(true);
        }
        cartService.addCart(cart);
        return  ResultTool.success();
    }
}
